package com.ruoyi.controller;

import cn.hutool.json.JSONObject;
import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.model.chat.ChatResponse;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.config.WebSocketManager;
import com.ruoyi.domain.*;
import com.ruoyi.enums.ConnectDeviceTypeEnum;
import com.ruoyi.enums.DelEnums;
import com.ruoyi.enums.WsCode;
import com.ruoyi.enums.WsType;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.service.*;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

@RequestMapping("/harmony/api")
@RestController
public class HarmonyController extends BaseController {

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IDeviceMainService deviceMainService;

    @Autowired
    private IUserAddressService userAddressService;

    @Autowired
    private IServiceMainService serviceMainService;

    @Autowired
    private IServicePeopleService servicePeopleService;

    @Autowired
    private IOrderService orderService;


    @Resource
    @Qualifier("QianFan")
    private Qianfan qianfan;

    WebSocketManager webSocketManager = WebSocketManager.INSTANCE;

    @PostMapping("login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        return AjaxResult.success(token);
    }

    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo() {
        LoginUser loginUser = getLoginUser();
        if (StringUtils.isNull(loginUser)) {
            return AjaxResult.error("未登录");
        }
        SysUser user = userService.selectUserById(loginUser.getUserId());
        UserInfoResp resp = new UserInfoResp();
        BeanUtils.copyBeanProp(resp, user);
        return AjaxResult.success(resp);
    }

    // 修改用户
    @PostMapping("/updateUser")
    public AjaxResult updateAvatar(@RequestBody SysUser sysUser) {
        LoginUser loginUser = getLoginUser();
        if (StringUtils.isNull(loginUser)) {
            return AjaxResult.error("未登录");
        }
        sysUser.setUserId(loginUser.getUserId());
        userService.updateUserByHarmony(sysUser);
        return AjaxResult.success("修改成功");
    }

    @PostMapping("/getOBSKey")
    public AjaxResult getOBSKey() {
        String filePath = new File("").getAbsolutePath() + "\\key.txt"; // 文件路径
        StringBuilder contentBuilder = new StringBuilder();

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String str;
            while ((str = br.readLine()) != null) {
                contentBuilder.append(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        String jsonString = contentBuilder.toString();
        JSONObject jsonObject = new JSONObject(jsonString);
        return AjaxResult.success(jsonObject);
    }

    //整体返回，时间等待长，用户体验一般
    @GetMapping("/Chat")
    public AjaxResult askmessage(String message) {

        if (StringUtils.isEmpty(message)) {
            return AjaxResult.error("请输入消息");
        }

        ChatResponse response = qianfan.chatCompletion()
                .model("ERNIE-Speed-128K")
                .addMessage("user", message)
                .temperature(0.7)
                .execute();
        return AjaxResult.success(response.getResult());
    }

    //流式返回数据，需要配合WebSocket进行返回数据到前端
    @PostMapping("/StreamChat")
    public AjaxResult askMessageStream(@RequestBody QianFanReq req) {

        if (StringUtils.isEmpty(req.getMessage())) {
            return AjaxResult.error("请输入消息");
        }
        // 获取请求的用户信息
        LoginUser user = SecurityUtils.getLoginUser();
        // 检查用户是否连接
        boolean isConnect = webSocketManager.isConnect(user.getUserId(), ConnectDeviceTypeEnum.MOBILE);
        if (!isConnect) {
            return AjaxResult.error("未连接WebSocket");
        }
        // 使用子线程进行执行
        new Thread(() -> {
            qianfan.chatCompletion()
                    .model("ERNIE-Speed-128K")
                    .addMessage("user", req.getMessage())
                    .temperature(0.7)
                    .executeStream()
                    .forEachRemaining(chatResponse -> {
                        QianFanResp resp = new QianFanResp();
                        resp.setCode(WsCode.SUCCESS.getCode());
                        resp.setEnd(chatResponse.getEnd());
                        resp.setMessage(WsType.CHAT.getType());
                        resp.setData(chatResponse.getResult());
                        WsResult wsResult = new WsResult.Builder()
                                .data(resp)
                                .code(WsCode.SUCCESS.getCode())
                                .type(WsType.CHAT.getType())
                                .build();
                        webSocketManager.sessionSend(user.getUserId(), wsResult, ConnectDeviceTypeEnum.MOBILE);
                    });

        }).start();
        return AjaxResult.success("发送成功");
    }

    @GetMapping("/deviceList")
    public TableDataInfo deviceList(DeviceMain deviceMain)
    {
        startPage();
        deviceMain.setUserId(SecurityUtils.getUserId());
        List<DeviceMain> list = deviceMainService.selectDeviceMainList(deviceMain);
        return getDataTable(list);
    }

    @PostMapping("/deviceAdd")
    public AjaxResult deviceAdd(@RequestBody DeviceMain deviceMain)
    {
        if(deviceMainService.selectDeviceMainBySn(deviceMain.getDeviceSn()) != null){
            return AjaxResult.error("设备编号已存在");
        }
        deviceMain.setUserId(SecurityUtils.getUserId());
        return toAjax(deviceMainService.insertDeviceMain(deviceMain));
    }

    @DeleteMapping("/deviceDelete/{id}")
    public AjaxResult deviceDelete(@PathVariable Long id)
    {
        return toAjax(deviceMainService.deleteDeviceMainById(id));
    }

    // 地址管理模块
    // 获取列表
    @GetMapping("/addressList")
    public TableDataInfo addressList(UserAddress userAddress) {
        startPage();
        userAddress.setUserId(SecurityUtils.getUserId());
        List<UserAddress> list = userAddressService.selectUserAddressList(userAddress);
        return getDataTable(list);
    }

    // 添加地址
    @PostMapping("/addressAdd")
    public AjaxResult addressAdd(@RequestBody UserAddress userAddress) {
        userAddress.setUserId(SecurityUtils.getUserId());
        userAddress.setDelFlag(DelEnums.STAY.getCode());
        return toAjax(userAddressService.insertUserAddress(userAddress));
    }

    // 删除地址
    @DeleteMapping("/addressDelete/{id}")
    public AjaxResult addressDelete(@PathVariable Long id) {
        UserAddress userAddress = userAddressService.selectUserAddressById(id);
        if (userAddress == null) {
            return AjaxResult.error("地址不存在");
        }
        return toAjax(userAddressService.deleteUserAddressById(id));
    }

    // 服务列表
    @GetMapping("/userServiceList")
    public TableDataInfo userServiceList(ServiceMain serviceMain)
    {
        startPage();
        List<ServiceMain> list = serviceMainService.selectServiceMainList(serviceMain);
        return getDataTable(list);
    }

    // 服务详情
    @GetMapping("/userServiceDetail/{id}")
    public AjaxResult userServiceDetail(@PathVariable Long id)
    {
        ServiceMain serviceMain = serviceMainService.selectServiceMainById(id);
        if(serviceMain == null){
            return AjaxResult.error("服务不存在");
        }
        // 查询服务人员
        ServicePeople people = new ServicePeople();
        people.setServiceId(id);
        List<ServicePeople> list = servicePeopleService.selectServicePeopleList(people);
        serviceMain.setServicePeopleList(list);
        return AjaxResult.success(serviceMain);
    }

    // 订单模块
    @PostMapping("/orderList")
    public TableDataInfo orderList(@RequestBody Order order)
    {
        startPage();
        order.setUserId(SecurityUtils.getUserId()); // 查询当前人的订单
        List<Order> list = orderService.selectOrderList(order);
        return getDataTable(list);
    }

    //下单
    @PostMapping("/orderAdd")
    public AjaxResult orderAdd(@RequestBody Order order)
    {
        return orderService.startOrder(order);
    }

    //支付完成调用
    @PostMapping("/payOrder")
    public AjaxResult payOrder(@RequestBody Order order) {
        return orderService.payOrder(order);
    }
    // 请求接单调用
    @PostMapping("/acceptOrder")
    public AjaxResult acceptOrder(@RequestBody Order order) {
        return orderService.acceptOrder(order);
    }
    //开始服务调用
    @PostMapping("/startService")
    public AjaxResult startService(@RequestBody Order order) {
        return orderService.startService(order);
    }
    //完成服务调用
    @PostMapping("/finishService")
    public AjaxResult finishService(@RequestBody Order order) {
        return orderService.finishService(order);
    }
    //取消订单调用
    @PostMapping("/cancelOrder")
    public AjaxResult cancelOrder(@RequestBody Order order) {
        return orderService.cancelOrder(order);
    }

    @GetMapping("/test")
    public AjaxResult test() {
        logger.info("后端测试成功");
        return AjaxResult.success("后端测试成功");
    }

    @GetMapping("/test2")
    public AjaxResult test2() {
        WsResult wsResult = new WsResult.Builder()
                .data("测试报警推送消息")
                .code(WsCode.SUCCESS.getCode())
                .type(WsType.DEVICE_WARN.getType())
                .build();
        webSocketManager.sessionSend(3L, wsResult, ConnectDeviceTypeEnum.PC);
        return AjaxResult.success("测试成功");
    }

}
